#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BUFFSIZE 32
#define SPACE    32
ssize_t mygetline (char **lineptr, size_t *n, FILE *stream);

int main (int argc, char **argv)
{
	char *ptr = NULL;
	size_t n = 0;
	while (1) {
		if (-1 == mygetline (&ptr, &n, stdin)) {
			break;
		}
		puts (ptr);
	}
	free (ptr);
	ptr = NULL;
	return 0;
}
ssize_t mygetline (char **lineptr, size_t *n, FILE *stream)
{
	char buf[BUFFSIZE] = {0};
	int bufcnt = 0;
	int i = 0;

	while (1) {
		memset (buf, '\0', BUFFSIZE);
		if (NULL == fgets (buf, BUFFSIZE, stream)){
			break;
		}
		//判读读出来多少个字节
		bufcnt  = strlen (buf);	
		if (bufcnt + i > *n) {
			*n += SPACE; 
			*lineptr = realloc (*lineptr, *n);
		} 
		//空间充足
		strncpy (*lineptr + i, buf, bufcnt);
		i += bufcnt;
		
		//判断是否包含'\n'
		if ((*lineptr)[i-1] == '\n') {
			break;
		}
	}
	if (feof (stream) || ferror(stream)){
		return -1;
	}
	return i;
}

